<template>
  <el-upload
    class="avatar-uploader"
    :action="upload.url"
    :show-file-list="false"
    :headers="upload.headers"
    :data="upload.data"
    :name="upload.name"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  </el-upload>
</template>

<script>
import { uploadUrl } from "../../api/api";
import { getToken } from "../../api/request";
export default {
  name:'ImageUpload',
  data() {
    return {
      uploadUrl,
      // 上传参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 上传的地址
        url: uploadUrl,
        headers: { Authorization: getToken() },
        name: "multipartFile",
      },
      imageUrl: "",
    };
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      console.log(123);
      this.$emit("getReqUrl",res,file)
    },
    beforeAvatarUpload(file) {
      const isJP = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      console.log(file);
      if (!isJP) {
        this.$message.error("上传头像图片只能是 JPG或PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJP && isLt2M;
    },
  },
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
